#include "CalServer.hpp"
#include "Protocal.hpp"

#include <memory>
#include <stdlib.h>
using namespace Server;
using namespace std;

static void Usage(string msg)
{
    cout << "\nUsage:\n\t" << msg << " local_port\n\n"
         << endl;
}

// 上层逻辑
// req 已经构建好了一个完整的请求对象,
// resp 将req中的数据提取出来，完成计算，填充回响对象
bool calBack(const Request &req, Response &resp)
{
    // 初始化
    resp._exitCode = OK;
    resp._result = OK;

    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
    {
        if (req._y == 0)
        {
            resp._exitCode = DIV_ERR;
        }
        else
        {
            resp._result = req._x / req._y;
        }
    }
    break;
    case '%':
    {
        if (req._y == 0)
        {
            resp._exitCode = MOD_ERR;
        }
        else
        {
            resp._result = req._x % req._y;
        }
    }
    break;
    default:
        resp._exitCode = OP_ERR;
        break;
    }

    return true;
}

// ./tcpserver 端口号(8080)
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    unique_ptr<CalServer> uts(new CalServer(port));
    uts->InitCalServer();
    uts->Start(calBack);
    return 0;
}